class Solution
{
public:
    int minOperations(vector<int> &nums1, vector<int> &nums2)
    {
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int sum1 = accumulate(nums1.begin(), nums1.end(), 0);
        int sum2 = accumulate(nums2.begin(), nums2.end(), 0);
        if (sum1 == sum2)
        {
            return 0;
        }
        if (sum1 < sum2)
        {
            nums1.swap(nums2);
            swap(sum1, sum2);
        }
        int diff = sum1 - sum2;
        auto num1Pos = nums1.rbegin();
        auto num2Pos = nums2.begin();
        int step = 0;
        while (diff > 0)
        {
            int maxDecrease = num1Pos == nums1.rend() ? -1 : *num1Pos - 1;
            int maxIncrease = num2Pos == nums2.end() ? -1 : 6 - *num2Pos;
            if (maxDecrease <= 0 && maxIncrease <= 0)
            {
                return -1;
            }
            if (maxDecrease > maxIncrease)
            {
                diff -= maxDecrease;
                ++num1Pos;
            }
            else
            {
                diff -= maxIncrease;
                ++num2Pos;
            }
            ++step;
        }
        return step;
    }
};